package sandbox.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import sandbox.meta.SiteInfoMeta;
import sandbox.model.SampleInfo;
import sandbox.model.SiteInfo;
import sandbox.model.Ranking.Counter;
import sandbox.service.RankingService;
import sandbox.service.SampleService;

public class IndexController extends Controller {

    @Override
    public Navigation run() {
        List<SiteInfo> siteList = Datastore.query(SiteInfoMeta.get()).asList();
        request.setAttribute("siteList", siteList);

        String key = asString("key");
        List<SampleInfo> sampleList = SampleService.getSamplesBySite((key == null || "".equals(key.trim())) ? null : Datastore.stringToKey(key));
        request.setAttribute("sampleList", sampleList);
        request.setAttribute("sampleMap", getDailySampleMap(sampleList));

//        for (SampleInfo sample : sampleList) {
//            sample.setTitle(sample.getTitle() + "(" + RankingService.getRanking(sample) + ")");
//        }

        List<Counter> ranking = RankingService.getRankingList();
        if (ranking != null) {
            if (ranking.size() > 10) {
                ranking = ranking.subList(0, 10);
            }
        }
        request.setAttribute("ranking", ranking);

        return forward("/index.jsp");
    }

    Map<Date, List<SampleInfo>> getDailySampleMap(List<SampleInfo> sampleList) {
        Map<Date, List<SampleInfo>> result = new LinkedHashMap<Date, List<SampleInfo>>();
        Date date = null;
        for (SampleInfo sample : sampleList) {
            date = getDate(sample);
            if (result.get(date) == null) {
                result.put(date, new ArrayList<SampleInfo>());
            }
            result.get(date).add(sample);
        }
        return result;
    }

    Date getDate(SampleInfo sample) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(sample.getTimestamp());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
}
